<template>
  <div>
    <el-form ref="loginRef" :model="loginFrom" :rules="loginRules" size="large">
      <el-form-item prop="username">
        <el-input v-model="loginFrom.username" clearable placeholder="请输入用户名">
          <template #prefix>
            <i class="el-icon-user" />
          </template>
        </el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input
          v-model="loginFrom.password"
          clearable
          type="password"
          placeholder="请输入密码"
          show-password
          autocomplete="new-password"
        >
          <template #prefix>
            <i class="el-icon-lock" />
          </template>
        </el-input>
      </el-form-item>
    </el-form>
    <div class="login-btn">
      <el-button round size="large" @click="resetForm"> 重置 </el-button>
      <el-button round size="large" type="primary" @click="login"> 登录 </el-button>
    </div>
    <div class="remenberPass">
      <el-checkbox
        v-model="remenberP"
        style="margin-right: 5px"
        @change="changeRemenber"
      ></el-checkbox>
      <span>记住密码</span>
    </div>
  </div>
</template>

<script>
import { loginApi } from '@/api';
import { initBtnApi } from '@/api/ownIndex';

export default {
  name: 'loginfrom',
  data() {
    return {
      remenberP: false,
      loginRules: {
        username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
      },
      loginFrom: {
        encrypttype: 0,
        username: '',
        password: ''
      }
    };
  },
  mounted() {
    // this.$refs.loginRef.$el.addEventListener('keydown', this.login);
    // 监听 enter 事件（调用登录）
    document.onkeydown = (e) => {
      e = window.event || e;
      if (e.code === 'Enter' || e.code === 'enter' || e.code === 'NumpadEnter') {
        console.log('按键');
        this.login();
      }
    };
    this.$store.dispatch('getSystemMusicList'); //获取系统音乐库
    this.$store.dispatch('getEquipList'); //获取音响设备列表

    const isRemenberP = JSON.parse(`${localStorage.getItem('usernameInfo')}`);
    if (isRemenberP == null) {
      //没有登录过
    } else {
      //登录过
      // if(isRemenberP.)
      if (isRemenberP.password == undefined) {
        // 没有记住密码,只保存用户名
        this.loginFrom.username = isRemenberP.username;
      } else {
        // 记住了密码和用户名
        this.loginFrom.username = isRemenberP.username;
        this.loginFrom.password = window.atob(isRemenberP.password);
        this.remenberP = true;
      }
    }
    // console.log(isRemenberP);
  },
  methods: {
    /**
     * @use 记住密码事件
     */

    changeRemenber(e) {
      this.remenberP = e;
      console.log(this.remenberP);
    },
    /**
     * @use 登录
     */
    async login() {
      if (!this.$refs.loginRef) return;
      this.$refs.loginRef.validate(async (valid) => {
        if (!valid) return;
        try {
          const res = await loginApi(this.loginFrom);
          const initBtnConfig = {
            code: 0,
            data: {
              btnLayout: {
                direction: 0,
                top: 16,
                width: 700,
                height: 300,
                left: 0
              },
              otherBtnLayout: {
                direction: 0,
                top: 16,
                width: 525,
                height: 300,
                left: 698
              },
              mainEquipt: {
                top: 80,
                width: 1462,
                height: 759,
                left: 0
              },
              mainMusic: {
                top: 80,
                width: 194,
                height: 759,
                right: 160
              }
            },
            msg: '获取成功'
          };
          if (res.code === 0) {
            localStorage.setItem('username', this.loginFrom.username);
            localStorage.setItem('admin', res.data.issuperadmin);

            const obj = {
              call: 1,
              stopCall: 1,
              paly: 1,
              stop: 1,
              changeVol: 1,
              uploadMusic: 1,
              importTime: 1,
              deviceManage: 1,
              map: 1
            };
            localStorage.setItem('userPermi', JSON.stringify(obj));
            if (`${localStorage.getItem('username')}` !== null) {
              this.$message({
                message: '登录成功',
                type: 'success'
              });

              try {
                // 登录成功如果用户选择了记住密码就记住密码，没有就记住账号
                if (this.remenberP) {
                  const userInfo = {
                    username: this.loginFrom.username,
                    password: window.btoa(this.loginFrom.password)
                  };
                  localStorage.setItem('usernameInfo', JSON.stringify(userInfo));
                } else {
                  const userInfo = {
                    username: this.loginFrom.username
                  };
                  localStorage.setItem('usernameInfo', JSON.stringify(userInfo));
                }
                await initBtnApi(initBtnConfig);
              } catch (error) {}

              this.$router.push('/home');
            } else {
              // location.reload();
            }
          } else {
            this.$message({
              message: res.msg,
              type: 'error'
            });
          }
        } catch (e) {
          console.log(e);
        }
      });
      // if (this.loginFrom.username == '' || this.loginFrom.password == '') {
      //   this.$message({
      //     message: '用户名或密码不能为空',
      //     type: 'error'
      //   });
      //   return;
      // }
    },

    /**
     * @use 重置
     */
    resetForm() {
      this.$refs.loginRef.resetFields();
    }
  }
};
</script>

<style scoped lang="scss">
// @import '../../login.scss';
@import './loginFrom.scss';
</style>
